package com.dtease.agent.common.utils;

import com.dtease.agent.core.exception.BizException;
import com.dtwave.dipper.dubhe.common.constant.SecretKeyEnum;
import com.dtwave.wolf.utils.BlowfishUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * Description: 密码动态加密
 *
 * @author: zhangsensen
 * Version: 1.0
 * Create Date Time: 2019/6/13 下午12:11.
 * Update Date Time:
 */
public class PasswordOperateUtils {

    /**
     * 密码动态加密
     * @param password 密码
     * @param credentials sk
     * @return
     */
    public static String encryptPassword(String password, Credentials credentials){

        if (null == credentials || StringUtils.isBlank(credentials.getSecretKey())){
            throw new BizException("密钥为空密码加密失败, 请联系运维人员排查");
        }

        String key = credentials.getSecretKey().length() > 10 ? credentials.getSecretKey().substring(0, 10)
                : credentials.getSecretKey();

        String result = BlowfishUtils.encryptBlowfish(password, key);
        return result;
    }

    /**
     * 密码动态解密
     * @param password 密码
     * @param credentials sk
     * @return
     */
    public static String decryptPassword(String password, Credentials credentials){
        if (null == credentials || StringUtils.isBlank(credentials.getSecretKey())){
            throw new BizException("密钥为空密码加密失败, 请联系运维人员排查");
        }

        String key = credentials.getSecretKey().length() > 10 ? credentials.getSecretKey().substring(0, 10)
                : credentials.getSecretKey();

        return BlowfishUtils.decryptBlowfish(password, key);
    }

    /**
     * 资源管理默认加密方式
     * @param password
     * @return
     */
    public static String encrypt(String password) {
        return BlowfishUtils.encryptBlowfish(password, SecretKeyEnum.DATA_SOURCE_KEY.getScertKey());
    }

    public static String decrypt(String password) {
        return BlowfishUtils.decryptBlowfish(password, SecretKeyEnum.DATA_SOURCE_KEY.getScertKey());
    }

}
